#!/bin/bash
# https://docs.sonarsource.com/sonarqube/9.9/analyzing-source-code/scanners/sonarscanner/

set -euo pipefail

#****** vars ******#
SS_VERSION="6.1.0.4477"
SS_INSTALL_PATH="/usr/local"
SS_SONAR_URL="http://10.0.0.26:9000"
color() {
    local message="$1"
    local status="$2"
    local terminal_width
    terminal_width=$(tput cols)
    local middle_column=$(( terminal_width / 2))
    local SETCOLOR_SUCCESS="\033[1;32m"  # 绿色
    local SETCOLOR_FAILURE="\033[1;31m"  # 红色
    local SETCOLOR_WARNING="\033[1;33m"  # 黄色
    local SETCOLOR_NORMAL="\033[0m"      # 重置颜色
    printf '%s\n\033[%sG' "${message}"  "${middle_column}"
    # Print the status message
    printf "["
    case ${status} in
        success|0)
            echo -en  "${SETCOLOR_SUCCESS}  OK  "
            ;;
        failure|1)
            echo -en  "${SETCOLOR_FAILURE}FAILED"
            ;;
        *)
            echo -en "${SETCOLOR_WARNING}WARNING"
            ;;
    esac
    echo -e "${SETCOLOR_NORMAL}]"
}

create_dir () {
    local i
    for i in "$@";do
        if [ ! -d "$i" ];then
            mkdir -pv "$i" && color "$i dir is created" 0
        else
            color "$i dir is existed." 2
        fi
    done
}

judge_current_user () {
    if [ "$(id -u)" = "0" ];then
        color "current user is administrator" 0
    else
        color "current user is not administrator" 1
        exit
    fi
}

process_ss_file () {
    create_dir $SS_INSTALL_PATH
    if ! [ -e "sonar-scanner-cli-${SS_VERSION}-linux-x64.zip" ];then
        color "current dir don't exist sonar-scanner-cli-${SS_VERSION}-linux-x64.zip" 1
        exit
    fi
    if ! command -v unzip &> /dev/null;then
        if grep -q 'ID_LIKE.*fedora' /etc/os-release;then
            yum install -y unzip || { color "yum install unzip failed." 1;exit; }
        elif  grep -q 'ID_LIKE.*debian' /etc/os-release;then   
            apt update
            apt install -y unzip || { color "apt install unzip failed." 1;exit; }
        fi
    fi

    unzip -o sonar-scanner-cli-${SS_VERSION}-linux-x64.zip -d $SS_INSTALL_PATH
    ln -nfs ${SS_INSTALL_PATH}/sonar-scanner-${SS_VERSION}-linux-x64 ${SS_INSTALL_PATH}/sonar-scanner
    chmod +x ${SS_INSTALL_PATH}/sonar-scanner/bin/*
}

config_ss () {
    local SS_CONFIG_FILE="${SS_INSTALL_PATH}/sonar-scanner/conf/sonar-scanner.properties"

    if grep -q '^sonar.host.url' $SS_CONFIG_FILE;then
        sed -i "/^sonar.host.url/c sonar.host.url=${SS_SONAR_URL}" $SS_CONFIG_FILE
    else
        echo "sonar.host.url=${SS_SONAR_URL}" >> $SS_CONFIG_FILE
    fi

    cat > /etc/profile.d/sonar-scanner.sh <<EOF
	export PATH=\$PATH:${SS_INSTALL_PATH}/sonar-scanner/bin
EOF
    color "安装完毕，
    执行 source /etc/profile.d/sonar-scanner.sh，后使用sonar-scanner命令." 0
}

main () {
    judge_current_user
    process_ss_file
    config_ss
}

main